package com.mission.game.creategame;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.mission.game.R;
import com.mission.game.components.DatePickerFragment;
import com.mission.game.components.TimePickerFragment;
import com.mission.game.utils.Game;
import com.mission.game.utils.Game.Visibility;

public class CreateNewGameScreen extends FragmentActivity {

	private static final String NAME_REQUIRED = "Game name is required, fill it in to continue.";
	Calendar _startDate;
	String _gameName;
	String _gameDescription;
	Visibility _gameVisibility = Visibility.PUBLIC;

	private Game _game;

	private TextView _tvDisplayDate;
	private TextView _tvDisplayTime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_new_game_screen);

		setStartDateAndTime();

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			if (extras.containsKey("game")) {
				_game = (Game) extras.getSerializable("game");
				setFields();
			} else {// Shouldn't get here.
				return;
			}
		}

		Spinner spinner = (Spinner) findViewById(R.id.game_visibility_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.visibility_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new VisibilityOnItemSelectedListener());
	}

	private void setFields() {
		setStartDateAndTime(_game.getStartDate());
		((EditText) findViewById(R.id.game_name_input))
				.setText(_game.getName());
		((EditText) findViewById(R.id.game_description_input)).setText(_game
				.getDescription());
		int pos = getVisibilityPosition(_game.getVisibility());
		((Spinner) findViewById(R.id.game_visibility_spinner))
				.setSelection(pos);
		((Button) findViewById(R.id.create_game_next_button_1))
				.setText("Return to missions");
	}

	private int getVisibilityPosition(Visibility visibility) {
		switch (visibility) {
		case PUBLIC:
			return 0;
		case PRIVATE:
			return 1;
		case GLOBAL:
			return 2;
		}
		return 0;
	}

	public class VisibilityOnItemSelectedListener implements
			OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			switch (pos) {
			case 0:
				_gameVisibility = Visibility.PUBLIC;
				break;
			case 1:
				_gameVisibility = Visibility.PRIVATE;
				break;
			case 2:
				_gameVisibility = Visibility.GLOBAL;
				break;
			default:
				break;
			}
		}

		public void onNothingSelected(AdapterView<?> parent) {
			// Do nothing.
		}
	}

	public void setStartDateAndTime() {
		_tvDisplayDate = (TextView) findViewById(R.id.start_date_input);
		_tvDisplayTime = (TextView) findViewById(R.id.start_time_input);
		final Calendar c = Calendar.getInstance();
		setStartDateAndTime(c);
	}

	public void setStartDateAndTime(final Calendar c) {
		_startDate = c;
		// set current date into textview
		_tvDisplayDate.setText(new StringBuilder()
				// Month is 0 based, just add 1
				.append(c.get(Calendar.MONTH) + 1).append("-")
				.append(c.get(Calendar.DAY_OF_MONTH)).append("-")
				.append(c.get(Calendar.YEAR)).append(" "));
		// set current time into textview
		StringBuilder timeText = new StringBuilder();
		timeText.append(c.get(Calendar.HOUR_OF_DAY)).append(":");
		if (c.get(Calendar.MINUTE) < 10) {
			timeText.append(0);
		}
		timeText.append(c.get(Calendar.MINUTE)).append(" ");
		_tvDisplayTime.setText(timeText);
	}

	public void showDatePickerDialog(View v) {
		DialogFragment newFragment = new DatePickerFragment(datePickerListener);
		newFragment.show(getSupportFragmentManager(), "datePicker");
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			// set selected date into textview
			_tvDisplayDate.setText(new StringBuilder()
					.append(selectedMonth + 1).append("-").append(selectedDay)
					.append("-").append(selectedYear).append(" "));
			// and into date field
			_startDate.set(selectedYear, selectedMonth, selectedDay);
		}
	};

	public void showTimePickerDialog(View v) {
		DialogFragment newFragment = new TimePickerFragment(timePickerListener);
		newFragment.show(getSupportFragmentManager(), "timePicker");
	}

	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {

		// when dialog box is closed, below method will be called.
		public void onTimeSet(TimePicker view, int selectedHour,
				int selectedMinute) {
			// set selected time into textview
			StringBuilder timeText = new StringBuilder();
			timeText.append(selectedHour).append(":");
			if (selectedMinute < 10) {
				timeText.append(0);
			}
			timeText.append(selectedMinute).append(" ");
			_tvDisplayTime.setText(timeText);
			// and into time field
			_startDate.set(Calendar.HOUR_OF_DAY, selectedHour);
			_startDate.set(Calendar.MINUTE, selectedMinute);
		}
	};

	public void goToNextScreen(View v) {
		_gameName = ((EditText) findViewById(R.id.game_name_input)).getText()
				.toString();
		_gameDescription = ((EditText) findViewById(R.id.game_description_input))
				.getText().toString();
		if (_gameName.equals("")) {
			Toast.makeText(getApplicationContext(), NAME_REQUIRED,
					Toast.LENGTH_LONG).show();
			((EditText) findViewById(R.id.game_name_input)).requestFocus();
			return;
		}
		if (_game == null) {
			_game = new Game(_gameName, _gameDescription, _startDate, true,
					_gameVisibility);
		} else {
			_game.setName(_gameName);
			_game.setDescription(_gameDescription);
			_game.setVisibility(_gameVisibility);
			_game.setStartDate(_startDate);
		}
		Intent i = new Intent(this, MissionControlScreen.class);
		i.putExtra("game", _game);
		startActivityForResult(i, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && data.getExtras() != null) {
			if (resultCode == MissionControlScreen.RESULT_EDIT) {
				_game = (Game) data.getExtras().get("game");
				setFields();
			}
			if (resultCode == RESULT_OK) {
				setResult(resultCode, data);
				finish();
			}
		}
	}
	
}